package com.yuanzi.base.auth;

import java.util.Map;
import java.util.Objects;

import org.springframework.stereotype.Service;

import com.yuanzi.base.constants.AuthConstants;
import com.yuanzi.base.redis.OuterHashRedisService;
import com.yuanzi.base.util.StringUtils;

/**
 * 权限缓存信号量(当相关权限有变化时，修改该信号量)
 * @author cui
 * @data 2017年10月9日
 */
@Service
public class AuthFlagRedisService {
	
	private static String serviceName = AuthConstants.AUTH_SERVICE_NAME;
	
	/**
	 * 获取相关权限是否最新标识位
	 * @author cui
	 * @param flagType
	 * @param memberId
	 * @return
	 */
	public static boolean isAuthNEW(String flagType, String memberId){
		String flag = AuthFlagRedisService.getAuthFlag(flagType, memberId);
		if(!StringUtils.isEmpty(flag)){
			return !Objects.equals(flag, AuthConstants.AUTH_IS_ALTERED);
		}
		return true;
	}
	
	/**
	 * 获取权限是否有修改
	 * @author cui
	 * @param flagType
	 * @param memberId
	 * @return
	 */
	public static String getAuthFlag(String flagType, String memberId){
		return OuterHashRedisService.hget(serviceName, AuthConstants.REDIS_AUTH_FLAG+flagType, memberId);
	}
	
	/**
	 * 
	 * @param flagType
	 * @param memberId
	 * @param objId
	 * @return
	 */
	public static String getAuthFlag(String flagType, String memberId, String objId){
		String secondKey = AuthConstants.REDIS_AUTH_FLAG + flagType + ":" + memberId;
		return OuterHashRedisService.hget(serviceName, secondKey, objId);
	}
	
	/**
	 * 当有权限有修改时，修改该信号量
	 * @author cui
	 * @param flagType
	 * @param memberId
	 * @param flag
	 */
	public static void setAuthFlag(String flagType, String memberId, String flag){
		OuterHashRedisService.hset(serviceName, AuthConstants.REDIS_AUTH_FLAG+flagType, memberId, flag);
	}
	
	/**
	 * 当有权限有修改时，修改该信号量(批量)
	 * @author cui
	 * @param flagType
	 * @param flagMap
	 */
	public static void setAuthFlagInBatch(String flagType, Map<String, String> flagMap){
		OuterHashRedisService.hmset(serviceName, AuthConstants.REDIS_AUTH_FLAG+flagType, flagMap);
	}
	
	/**
	 * 将信号量恢复默认值(AUTH_NO_ALTERED)
	 * @author cui
	 * @param memberId
	 * @param authFlagType
	 */
	public static void setCourseAuthFlagDefault(String memberId, String authFlagType){
		OuterHashRedisService.hset(serviceName, AuthConstants.REDIS_AUTH_FLAG+authFlagType, memberId, AuthConstants.AUTH_NO_ALTERED);
	}
}
